<template>
  <div class="app-container">
    <el-tabs type="border-card">
      <el-tab-pane label="ROI统计">
        <div class="filter-container">
          <el-select
            v-model="listQuery.channelId"
            filterable
            clearable
            :filter-method="dataFilter"
            placeholder="选择渠道"
            style="width: 150px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          >
            <el-option
              v-for="item in options"
              :key="item.channelId"
              :label="item.channel_name"
              :value="item.channelId"
            />
          </el-select>
          <el-date-picker
            v-model="times"
            class="filter-item"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 250px;"
            type="daterange"
            value-format="yyyy-MM-dd"
          />
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >
            搜索
          </el-button>
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-download"
            :loading="channelBtn"
            @click="handleExport"
          >
            导出
          </el-button>
        </div>
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="tableData"
          border
          fit
          highlight-current-row
          style="width: 100%;"
        >
          <el-table-column label="时间" min-width="110" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.registerDate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="渠道名称" min-width="150" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.nickname }}</span>
            </template>
          </el-table-column>
          <el-table-column label="机构进件数" min-width="100" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.agencyNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="机构收益" min-width="110" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.agencyAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="API进件数" align="center" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="showClickAps(scope)">{{
                incomeData[scope.$index].clickAps
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="API收益" min-width="100" align="center">
            <template slot-scope="scope">
              <span>{{ incomeData[scope.$index].clickApsAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="贷超点击" align="center" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="showClickNum(scope)">{{
                incomeData[scope.$index].clickNum
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="贷超收益" min-width="100" align="center">
            <template slot-scope="scope">
              <span>{{ incomeData[scope.$index].clickAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="UV" min-width="80" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.channelUv }}</span>
            </template>
          </el-table-column>
          <el-table-column label="渠道支出" min-width="80" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.outlay }}</span>
            </template>
          </el-table-column>
          <el-table-column label="渠道总收益" min-width="100" align="center">
            <template slot-scope="scope">
              <span>{{ incomeData[scope.$index].income }}</span>
            </template>
          </el-table-column>
          <el-table-column label="利润" min-width="100" align="center">
            <template slot-scope="scope">
              <span>{{ incomeData[scope.$index].profit }}</span>
            </template>
          </el-table-column>
          <el-table-column label="ROI" min-width="100" align="center">
            <template slot-scope="scope">
              <span>{{ incomeData[scope.$index].roi }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.current"
          :limit.sync="listQuery.size"
          @pagination="statisticalSep"
        />
      </el-tab-pane>
      <el-dialog
        title="API收益"
        :visible.sync="apsVisible"
        :close-on-click-modal="false"
      >
        <el-table
          v-loading="loading"
          :data="apsData"
          style="width: 800px"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="channel" label="产品名" width="150">
          </el-table-column>
          <el-table-column label="价格" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="apsData[scope.$index].p"
                autocomplete="off"
                style="width: 100px;"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="c" label="数量" width="120"> </el-table-column>
          <el-table-column label="收益" width="150">
            <template slot-scope="{ row }">
              {{ row.c * row.p }}
            </template>
          </el-table-column>
        </el-table>
        <div style="margin: 10px 0;">总收益：{{ apsTotalRevenue }}</div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="apsVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateAps()">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="贷超收益"
        :visible.sync="loanVisible"
        :close-on-click-modal="false"
      >
        <el-table
          v-loading="loading"
          :data="loanData"
          style="width: 800px"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="app_name" label="产品名" width="150">
          </el-table-column>
          <el-table-column label="价格" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="loanData[scope.$index].price"
                autocomplete="off"
                style="width: 100px;"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="unique" label="数量" width="120">
          </el-table-column>
          <el-table-column label="收益" width="150">
            <template slot-scope="{ row }">
              {{ row.unique * row.price }}
            </template>
          </el-table-column>
        </el-table>
        <div style="margin: 10px 0;">总收益：{{ loanTotalRevenue }}</div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="loanVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateLoan()">确 定</el-button>
        </div>
      </el-dialog>
    </el-tabs>
  </div>
</template>

<script>
import { getChannelIdAndNick } from '@/api/user';
import {
  getChannelRoi,
  doExcelChannelRoi,
  getApsByRoi,
  getLoanByRoi
} from '@/api/auth';
import { timestampToTimeYear } from '@/utils/index';
import waves from '@/directive/waves'; // waves directive
import Pagination from '@/components/Pagination'; // secondary package based on el-pagination
export default {
  name: 'CountChannel',
  components: { Pagination },
  directives: { waves },
  filters: {
    number(value) {
      return parseFloat(value).toFixed(2);
    },
    dateFormat(value) {
      if (value !== null && value !== '') {
        return value.split(' ')[0];
      } else {
        return '';
      }
    }
  },
  data() {
    return {
      tableData: [],
      incomeData: [],
      dayData: [],
      total: 0,
      daytotal: 0,
      tableKey: 0,
      listQuery: {
        current: 1,
        size: 10
      },
      times: [],
      timeNow: [
        new Date(new Date().toLocaleDateString()).getTime(),
        new Date(new Date().toLocaleDateString()).getTime() +
          24 * 60 * 60 * 1000
      ],
      optionsCopy: [],
      options: [],
      nowIndex: 0,
      apsData: [],
      loanData: [],
      apsTotalRevenue: '',
      loanTotalRevenue: '',
      formLabelWidth: 100,
      tabActive: '0',
      apsVisible: false,
      loanVisible: false,
      listLoading: false,
      loading: false,
      channelBtn: false
    };
  },
  watch: {
    apsData: {
      handler: function(newV, oldV) {
        let sum = 0;
        this.apsData.forEach(item => {
          if (item.c * item.p !== 'NaN') {
            sum += item.c * item.p;
          }
        });
        this.apsTotalRevenue = sum;
      },
      deep: true,
      immediate: true
    },
    loanData: {
      handler: function(newV, oldV) {
        let sum = 0;
        this.loanData.forEach(item => {
          if (item.unique * item.price !== 'NaN') {
            sum += item.unique * item.price;
          }
        });
        this.loanTotalRevenue = sum;
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.times = [
      timestampToTimeYear(this.timeNow[0]),
      timestampToTimeYear(this.timeNow[1])
    ];
    this.listQuery.endTime = this.times[1];
    this.listQuery.startTime = this.times[0];
    this.statisticalSep();
    this.getChannelIdAndNick();
  },
  methods: {
    updateAps() {
      this.incomeData[this.nowIndex].clickApsAmount = this.apsTotalRevenue;
      this.apsVisible = false;
      this.updateTableDate();
    },
    updateLoan() {
      this.incomeData[this.nowIndex].clickAmount = this.loanTotalRevenue;
      this.loanVisible = false;
      this.updateTableDate();
    },
    updateTableDate() {
      this.incomeData.map(item => {
        item.income = (
          item.agencyAmount +
          item.clickApsAmount +
          item.clickAmount
        ).toFixed(2);
        item.profit = (item.income - item.outlay).toFixed(2);
        item.roi = (item.income / item.outlay).toFixed(2);
      });
    },
    // 渠道下拉
    dataFilter(val) {
      this.value = val;
      if (val) {
        // val存在
        this.options = this.optionsCopy.filter(item => {
          if (
            !!~item.channel_name.indexOf(val) ||
            !!~item.channel_name.toUpperCase().indexOf(val.toUpperCase())
          ) {
            return true;
          }
        });
      } else {
        // val为空时，还原数组
        this.options = this.optionsCopy;
      }
    },
    async getChannelIdAndNick() {
      const res = await getChannelIdAndNick(this.listQuery);
      res.data.data.forEach(element => {
        if (element.channel_name !== null) {
          this.optionsCopy.push(element);
          this.options.push(element);
        }
      });
    },
    // 获取列表
    async statisticalSep() {
      if (this.times == null || this.times.length === 0) {
        this.listQuery.endTime = '';
        this.listQuery.startTime = '';
      } else {
        this.listQuery.endTime = this.times[1];
        this.listQuery.startTime = this.times[0];
      }
      const res = await getChannelRoi(this.listQuery);
      this.tableData = res.data.data.records;
      this.incomeData = this.tableData;
      this.total = res.data.data.total;
    },
    async showClickAps(scope) {
      this.nowIndex = scope.$index;
      const params = {
        channelId: scope.row.channelId,
        startTime: scope.row.registerDate
      };
      const res = await getApsByRoi(params);
      if (res.data.code === 200) {
        this.apsData = res.data.data;
        this.apsVisible = true;
      }
    },
    async showClickNum(scope) {
      this.nowIndex = scope.$index;
      const params = {
        channelId: scope.row.channelId,
        startTime: scope.row.registerDate
      };
      const res = await getLoanByRoi(params);
      if (res.data.code === 200) {
        this.loanData = res.data.data;
        this.loanVisible = true;
      }
    },
    // 搜索
    handleFilter() {
      this.listQuery.current = 1;
      if (this.tabActive === '0') {
        this.statisticalSep(this.listQuery);
      }
    },
    handleExport() {
      this.channelBtn = true;
      if (this.times == null || this.times.length === 0) {
        this.listQuery.endTime = '';
        this.listQuery.startTime = '';
      } else {
        this.listQuery.endTime = this.times[1];
        this.listQuery.startTime = this.times[0];
      }
      doExcelChannelRoi(this.listQuery).then(res => {
        if (res.data.code === 200) {
          this.channelBtn = false;
          window.location.href = res.data.data;
        } else {
          this.channelBtn = false;
          this.$notify({
            title: '错误',
            message: '导出失败，请联系后台技术人员',
            type: 'fail',
            duration: 2000
          });
        }
      });
    }
  }
};
</script>
